package com.yq.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yq.constant.GatewayConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Configuration
public class RouteConfig {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Bean
    public RouteLocator gatewayLocator(RouteLocatorBuilder builder){
       return builder.routes().route("oauth-route-id",r->r.path("/oauth/token")
                .filters(f->f.modifyResponseBody(String.class,String.class,(exchange,s)->{
                    JSONObject jsonObject = JSON.parseObject(s);
                    String token = jsonObject.getString(GatewayConstants.ACCESS_TOKEN);
                    if (StringUtils.hasText(token)){
                        Long expireIn = jsonObject.getLong(GatewayConstants.EXPIRE_IN);
                        redisTemplate.opsForValue().set(GatewayConstants.OAUTH_JWT+token,"", Duration.ofSeconds(expireIn));
                    }
                    return Mono.just(s);
                })).uri("lb://auth-server")).build();
    }

}
